package com.wbao.dianniu.manager;

import android.content.Context;

import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.http.Batch;
import com.wbao.dianniu.http.Command;
import com.wbao.dianniu.http.HttpUtil;
import com.wbao.dianniu.http.HttpUtil.MyResponse;
import com.wbao.dianniu.listener.ILogin;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.logical.Action;
import com.wbao.dianniu.utils.JsonUtil;

import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;

public class LoginManager implements ILogin {

    private ILoginListener mListener = null;
    private Context mContext;

    public LoginManager(Context context) {
        mContext = context;
    }

    @Override
    public boolean addLoginListener(ILoginListener listener) {
        mListener = listener;
        return mListener == null ? false : true;
    }

    @Override
    public boolean removeLoginListener(ILoginListener listener) {
        if (null == listener)
            return false;
        mListener = null;
        return true;
    }

    @Override
    public void Login(Context context, final String mobile, String pwd, String deviceId, String longitude, String latitude, String appVersion, String smsCode) {
        // 向平台发送登录请求
        StringEntity stringEntity = null;
        try {
            Command command = new Command();
            command.addAction(Action.ACTION_LOGIN)
                    .addArgs("mobile", mobile)
                    .addArgs("pwd", pwd)
                    .addArgs("deviceType", "a")
                    .addArgs("deviceId", deviceId)
                    .addArgs("longitud", longitude)
                    .addArgs("latitude", latitude)
                    .addArgs("appVersion", appVersion)
                    .addArgs("smsCode", smsCode);
            stringEntity = new StringEntity(Batch.build().addCommand(command).toJson(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        HttpUtil http = new HttpUtil();
        http.req(context, stringEntity, false, new MyResponse() {

            @Override
            public void responseSucess(Object obj) {
                // TODO Auto-generated method stub
                LoginResponse resp = JsonUtil.toObject(obj, LoginResponse.class);
                // 通知界面
                if (null != mListener)
                    mListener.onLoginSuccess(resp);
            }

            @Override
            public void responseFailure(int errorCode, String msg) {
                // TODO Auto-generated method stub
                if (null != mListener)
                    mListener.onLoginFailure(errorCode, msg);
            }
        });
    }

}
